// @ts-nocheck
import ajax from './ajax';
import { getToken, removeToekn, removeUserStorageInfo } from './storage';
import utils from '../helper/utils';
import { setToken } from "./storage.js";
import { setUserStroageInfo, getUserStroageInfo } from "./storage.js";
import LoginEvent from "../events/loginEvent.js";

/**
 * 登录（没有则注册）
 * @param {string} userName 用户名（手机号）
 * @param {string} password 密码
 * @returns 
 */
export const login = (userName, password) => {
    const options = {
        'method': 'POST',
        'url': `/login`,
        data: {
            userName,
            password
        }
    }
    return ajax.fetch(options).then(async (res) => {
        const { token } = res;
        await setToken(token);
        const userInfo = await getUserInfo();
        LoginEvent.dispatchLoginEvent(userInfo);

        return userInfo;
    });
}

/**
 * 退出
 */
export const logout = async () => {
    // 删除必要的缓存
    await removeToekn();
    await removeUserStorageInfo();
    LoginEvent.dispatchLoginEvent(null);
}

/**
 *  获取当前登录用户信息
 */
export const getUserInfo = async () => {
    const token = await getToken();
    if (!token) {
        throw utils.newError(401, "未登录");
    }
    const options = {
        'method': 'POST',
        'url': `/user-info`
    }
    return ajax.fetch(options).then(async res => {
        const userInfo = await getUserStroageInfo();
        await setUserStroageInfo({ ...userInfo, ...res });
        return res;
    });
}

/**
 * 更新用户信息
 * @param {*} params 
 */
export const updateUserInfo = async (params) => {
    const options = {
        'method': 'POST',
        'url': `/update-user`,
        data: params
    }
    return ajax.fetch(options).then(async res => {
        const userInfo = await getUserStroageInfo();
        await setUserStroageInfo({ ...userInfo, ...res });
        return res;
    });
}